import os
import sys

def get_platform():
    platform = sys.platform
    if platform.startswith("linux"):
        return "linux"
    elif platform.startswith("win"):
        return "windows.exe"
    elif platform.startswith("darwin"):
        return "mac"
    else:
        return platform
    
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
# 把 db 放到系统 /tmp/cold_start_analyzer_db 目录下
DB_DIR = os.path.join(os.path.expanduser("~"), "tmp/cold_start_analyzer_db")
if not os.path.exists(DB_DIR):
    os.makedirs(DB_DIR)
EXE_PATH = os.path.join(CURRENT_DIR, f"bin/trace_streamer_{get_platform()}")

def convert_ftrace_to_sqlite(file_path):
    ftrace_name = os.path.basename(file_path)
    file_abs_path = os.path.abspath(file_path)
    target_name = os.path.abspath(f"{DB_DIR}/{ftrace_name}.db")
    if os.path.exists(target_name):
        return target_name
    try:
        command = f"{EXE_PATH} {file_abs_path} -e {target_name}"
        ret = os.system(command)
        if ret != 0:
            raise Exception(f"Failed to convert ftrace to sqlite: {ret}, command: {command}")
        return target_name
    except Exception as e:
        print(f"Error converting ftrace to sqlite: {e}")
        return None
